//
//  FoundViewController.m
//  Community
//
//  Created by YaSha_Tom on 2018/12/20.
//  Copyright © 2018年 YaSha-Tom. All rights reserved.
//

#import "FoundViewController.h"
#import "FoundCollectionViewCell.h"
#import "StrategyViewController.h"
#import <AFNetworking.h>
#import <QMUIKit.h>
#import "DataManager.h"
#import "FoundModel.h"
#import "UIImageView+WebCache.h"
#import "UIImage+LX.h"

static NSString *const reuseIdentifierHeader = @"ApplicationCycleView";
static NSString *const reuseIdentifier = @"ApplicationCell";

@interface FoundViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, strong) NSMutableArray *domesticDataSource;
@property (nonatomic, strong) NSMutableArray *foreignDataSource;
@property (nonatomic, strong)NSArray *titleArray;
@end

@implementation FoundViewController
- (NSMutableArray *)domesticDataSource {
    if (!_domesticDataSource) {
        _domesticDataSource = [NSMutableArray array];
    }
    return _domesticDataSource;
}
- (NSMutableArray *)foreignDataSource {
    if (!_foreignDataSource) {
        _foreignDataSource = [NSMutableArray array];
    }
    return _foreignDataSource;
}
- (UICollectionViewFlowLayout *)flowLayout {
    if (!_flowLayout) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.itemSize = CGSizeMake((375-20)/3.0, (375-20)/3.0);
        flowLayout.minimumInteritemSpacing = 5;
        flowLayout.minimumLineSpacing = 5;
//        flowLayout.minimumLineSpacing = 0;
//        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.headerReferenceSize = CGSizeMake(375, 30);
        flowLayout.sectionInset = UIEdgeInsetsMake(5, 5,5, 5);
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
        _flowLayout = flowLayout;
    }
    return _flowLayout;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"热门推荐";
    self.view.backgroundColor = [UIColor whiteColor];
    [self initUI];
    [self doNetworking];
    [self setupNavBar];
}
- (void)setupNavBar {
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage getImageWithColor:[UIColor qmui_colorWithHexString:@"E7494D"]] forBarMetrics:UIBarMetricsDefault];
    
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
}
- (void)doNetworking {
    // 1.创建请求管理对象
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    NSString *url = @"http://q.chanyouji.com/api/v1/search/featured.json";
    [manger GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"成功%@",responseObject);
        if ([responseObject[@"status"]  isEqual: @200]) {
            self.dataSource = [DataManager getAddressData:responseObject[@"data"]];
            [self dataProcessing];
        }else{
            [QMUITips showSucceed:@"请求数据失败" inView:self.view hideAfterDelay:1];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败%@",error);
    }];
}
- (void)dataProcessing {
    for (FoundModel *model in self.dataSource) {
        if ([model.name isEqualToString:@"上海"]||[model.name isEqualToString:@"西藏"]||[model.name isEqualToString:@"四川"]||[model.name isEqualToString:@"云南"]) {
            [self.domesticDataSource addObject:model];
        }
        if ([model.name isEqualToString:@"美国"]||[model.name isEqualToString:@"泰国"]||[model.name isEqualToString:@"韩国"]||[model.name isEqualToString:@"日本"]) {
            [self.foreignDataSource addObject:model];
        }
    }
      self.titleArray = @[@"国内热门",@"国外热门"];
    [self.collectionView reloadData];
}
- (void)initUI {
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 375, 667) collectionViewLayout:self.flowLayout];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.indicatorStyle = UIScrollViewIndicatorStyleBlack;
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:reuseIdentifierHeader];
    [self.collectionView registerClass:[FoundCollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
    [self.view addSubview:self.collectionView];
}
//分区个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 2;
}
//每个分区item的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 4;
}
/**
 创建cell
 */
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    FoundCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    if (indexPath.section == 0 && self.domesticDataSource.count > 0) {
        FoundModel *model  = self.domesticDataSource[indexPath.row];
        cell.nameLabel.text = model.name;
        [cell.headerImage sd_setImageWithURL:[NSURL URLWithString:model.photo_url] placeholderImage:[UIImage imageNamed:@" "]];
    }
    if (indexPath.section == 1 && self.foreignDataSource.count > 0){
        FoundModel *model  = self.foreignDataSource[indexPath.row];
        cell.nameLabel.text = model.name;
        [cell.headerImage sd_setImageWithURL:[NSURL URLWithString:model.photo_url] placeholderImage:[UIImage imageNamed:@" "]];
    }
    
    return cell;
}

/**
 创建区头视图和区尾视图
 */
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
  
    UILabel *titleLabel;
    if (kind == UICollectionElementKindSectionHeader){
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:reuseIdentifierHeader forIndexPath:indexPath];
        headerView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        [titleLabel removeFromSuperview];
        titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 5, 347, 20)];
        if (self.titleArray.count > 0) {
            titleLabel.text = self.titleArray[indexPath.section];
        }
        [headerView addSubview:titleLabel];
        return headerView;
    }
    return nil;
    
    
}
/**
 点击某个cell
 */
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"点击了第%ld分item",(long)indexPath.item);
    StrategyViewController *strategyViewController  =[[StrategyViewController alloc]init];
    FoundModel *model;
    if(indexPath.section == 0){
        model = self.domesticDataSource[indexPath.row];
    }else{
        model = self.foreignDataSource[indexPath.row];
    }
    strategyViewController.titleStr = model.name;
    strategyViewController.id = model.id;
    [self.navigationController pushViewController:strategyViewController animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
